import sys
import os
import subprocess

def CreateGlobalVarialbe():
	global g_szSoftwareName
	global g_szVersionNum
	global g_bBackend

	g_szSoftwareName = '文件夹同步'
	g_szVersionNum = 'v1.2.4'
	g_bBackend = 0
	return 0
def CombineDirectory(szSourceDir, szTargetDir, szModeSelect):
	bResultCombined = 1
	iCopyFilesCount = 0

	# Check directory
	if(os.path.isdir(szSourceDir) and os.path.isdir(szTargetDir)):
		pass
	else:
		if(g_bBackend):
			pass
		else:
			print('\n输入目录或输出目录不存在，进程已结束。\n')
		bResultCombined = 0
		return bResultCombined, iCopyFilesCount
	
	# Get all files name
	lszEachFilePathsName_Source = []
	lszEachFilePathsName_Target = []
	genWalkResult_Source = os.walk(szSourceDir)
	for root, dirs, files in genWalkResult_Source:
		if(files):
			for eachFile in files:
				lszEachFilePathsName_Source.append(os.path.join(root,eachFile))
		else:
			pass
	genWalkResult_Target = os.walk(szTargetDir)
	for root, dirs, files in genWalkResult_Target:
		if(files):
			for eachFile in files:
				lszEachFilePathsName_Target.append(os.path.join(root,eachFile))
		else:
			pass
	# print(lszEachFilePathsName_Source)
	# print(lszEachFilePathsName_Target)
	if(szModeSelect == '1'):
		# 镜像：左-->右
		if(lszEachFilePathsName_Source):
			for szEachFilePath in lszEachFilePathsName_Source:
				tempFileName = os.path.basename(szEachFilePath)
				tempDir_Source = os.path.dirname(szEachFilePath)
				tempDir_Target = tempDir_Source.replace(szSourceDir, szTargetDir)
				# print(tempDir_Source)
				if(os.path.isdir(tempDir_Target) == False):
					os.makedirs(tempDir_Target)
				else:
					pass
				if(szEachFilePath.replace(szSourceDir, szTargetDir) in lszEachFilePathsName_Target):
					if(g_bBackend):
						pass
					else:
						print('[%s]已存在，跳过。' % szEachFilePath)
					pass
				else:
					# print('[%s]不存在，复制。' % szEachFilePath)
					temp_szCMDLine = 'copy "%s" "%s"' % (os.path.join(tempDir_Source, tempFileName), os.path.join(tempDir_Target, tempFileName))
					# print(temp_szCMDLine)
					try:
						if(g_bBackend):
							subprocess.run(temp_szCMDLine, creationflags = subprocess.CREATE_NO_WINDOW, shell = True)
						else:
							os.system(temp_szCMDLine)
					except Exception as e:
						if(g_bBackend):
							pass
						else:
							print('[%s]复制失败。' % szEachFilePath)
							print(e)
					else:
						# print(temp_szCMDLine)
						iCopyFilesCount += 1
		else:
			pass
		# 镜像：右-->左
		if(lszEachFilePathsName_Target):
			for szEachFilePath in lszEachFilePathsName_Target:
				tempFileName = os.path.basename(szEachFilePath)
				tempDir_Source = os.path.dirname(szEachFilePath)
				tempDir_Target = tempDir_Source.replace(szTargetDir, szSourceDir)
				# print(tempDir_Source)
				# print(tempDir_Target)
				if(os.path.isdir(tempDir_Target) == False):
					os.makedirs(tempDir_Target)
				else:
					pass
				if(szEachFilePath.replace(szTargetDir, szSourceDir) in lszEachFilePathsName_Source):
					if(g_bBackend):
						pass
					else:
						print('[%s]已存在，跳过。' % szEachFilePath)
					pass
				else:
					# print('[%s]不存在，复制。' % szEachFilePath)
					temp_szCMDLine = 'copy "%s" "%s"' % (os.path.join(tempDir_Source, tempFileName), os.path.join(tempDir_Target, tempFileName))
					# print(temp_szCMDLine)
					try:
						if(g_bBackend):
							subprocess.run(temp_szCMDLine, creationflags = subprocess.CREATE_NO_WINDOW, shell = True)
						else:
							os.system(temp_szCMDLine)
					except Exception as e:
						if(g_bBackend):
							pass
						else:
							print('[%s]复制失败。' % szEachFilePath)
							print(e)
					else:
						# print(temp_szCMDLine)
						iCopyFilesCount += 1
	elif(szModeSelect == '2'):
		# 追加：左-->右
		if(lszEachFilePathsName_Source):
			for szEachFilePath in lszEachFilePathsName_Source:
				tempFileName = os.path.basename(szEachFilePath)
				tempDir_Source = os.path.dirname(szEachFilePath)
				tempDir_Target = tempDir_Source.replace(szSourceDir, szTargetDir)
				# print(tempDir_Source)
				if(os.path.isdir(tempDir_Target) == False):
					os.makedirs(tempDir_Target)
				else:
					pass
				if(szEachFilePath.replace(szSourceDir, szTargetDir) in lszEachFilePathsName_Target):
					if(g_bBackend):
						pass
					else:
						print('[%s]已存在，跳过。' % szEachFilePath)
					pass
				else:
					# print('[%s]不存在，复制。' % szEachFilePath)
					temp_szCMDLine = 'copy "%s" "%s"' % (os.path.join(tempDir_Source, tempFileName), os.path.join(tempDir_Target, tempFileName))
					# print(temp_szCMDLine)
					try:
						if(g_bBackend):
							subprocess.run(temp_szCMDLine, creationflags = subprocess.CREATE_NO_WINDOW, shell = True)
						else:
							os.system(temp_szCMDLine)
					except Exception as e:
						if(g_bBackend):
							pass
						else:
							print('[%s]复制失败。' % szEachFilePath)
							print(e)
					else:
						# print(temp_szCMDLine)
						iCopyFilesCount += 1
		else:
			pass
	else:
		if(g_bBackend):
			pass
		else:
			print('\n模式选择错误，进程已结束。\n')
		bResultCombined = 0

	return bResultCombined, iCopyFilesCount



if __name__ == '__main__':
	CreateGlobalVarialbe()
	# Mode
	# 1: 镜像--文件名
	# 2: 追加--文件名

	# System argv
	try:
		szSourceDir = sys.argv[1]
	except Exception as e:
		if(g_bBackend):
			szSourceDir = ''
		else:
			print('\n未检测到启动参数"源路径",请手动输入：\n')
			szSourceDir = input()
	else:
		pass
	try:
		szTargetDir = sys.argv[2]
	except Exception as e:
		if(g_bBackend):
			szTargetDir = ''
		else:
			print('\n未检测到启动参数"目标路径",请手动输入：\n')
			szTargetDir = input()
	else:
		pass
	try:
		szModeSelect = sys.argv[3]
	except Exception as e:
		if(g_bBackend):
			szModeSelect = ''
		else:
			print('\n未检测到启动参数"模式选择",请手动输入：\n[1:镜像模式, 2:追加模式]\n')
			szModeSelect = input()
	else:
		pass
	
	if(g_bBackend):
		if(szSourceDir and szTargetDir and szModeSelect):
			pass
		else:
			sys.exit(0)
	else:
		print(szSourceDir)
		print(szTargetDir)
		print(szModeSelect)
	
	# Test
	# szSourceDir = 'D:/NameSpace/Desktop/Test'
	# szTargetDir = 'D:/NameSpace/Desktop/Target'
	# szModeSelect = '2'

	(bResult, iFilesCount) = CombineDirectory(szSourceDir, szTargetDir, szModeSelect)
	if(bResult):
		if(szModeSelect == '1'):
			if(g_bBackend):
				pass
			else:
				print('\n[%s]<-->[%s]\n镜像同步完成。\n已复制[%d]个文件。\n' %(szSourceDir, szTargetDir, iFilesCount))
		else:
			if(g_bBackend):
				pass
			else:
				print('\n[%s]-->[%s]\n追加同步完成。\n已复制[%d]个文件。\n' %(szSourceDir, szTargetDir, iFilesCount))
	else:
		if(g_bBackend):
			pass
		else:
			print('\n同步失败。\n')

	if(g_bBackend):
		pass
	else:
		print('\n按任意键退出...\n')
		input()